package com.lancoo.znbkxx.teacher.aibkTestCoach.kBase

import android.content.Context
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.jaeger.library.StatusBarUtil
import com.lancoo.znbkxx.teacher.utils.ButtonUtils.isFastDoubleClick
import com.lancoo.znbkxx.teacher.widget.LoadingDialog
import kotlinx.android.synthetic.main.aibk_activity_paper_preview.*
import me.jessyan.autosize.internal.CustomAdapt

abstract class KBaseActivity: AppCompatActivity(), CustomAdapt {

    private val loadingDialog by lazy { LoadingDialog(this) }

    fun startLoad() = loadingDialog.show()

    fun startLoad(msg: String) = loadingDialog.show(msg)

    fun stopLoad() = loadingDialog.dismiss()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(setLayout())
        initData()
        initView()
        StatusBarUtil.setTransparentForImageView(this, null)
        RlTopbar?.setPadding(0, getStatusBarHeight(this), 0, 0) //适配刘海屏
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //不息屏
    }

    // 设置布局
    protected abstract fun setLayout(): Int

    // 初始化组件
    protected abstract fun initView()

    protected abstract fun initData()


    fun getHolderActivity(): AppCompatActivity? {
        return this
    }

    override fun isBaseOnWidth(): Boolean {
        return false
    }

    override fun getSizeInDp(): Float {
        return 667F
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    open fun getStatusBarHeight(context: Context): Int {
        var statusBarHeight = 0
        val resourceId =
                context.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            statusBarHeight = context.resources.getDimensionPixelSize(resourceId)
        }
        return statusBarHeight
    }

    //请求状态码
    private val REQUEST_PERMISSION_CODE = 1
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (i in permissions.indices) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i])
            }
        }
    }

    /**
     * 重写点击事件
     * @param ev
     * @return
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            //防止短时间内多次点击
            if (isFastDoubleClick) {
                return true
            }
            //实现软键盘点击空白处自动回收
            val v = currentFocus //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v!!.windowToken) //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     * @param v
     * @param event
     * @return
     */
    open fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {  //判断得到的焦点控件是否包含EditText
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            //得到输入框在屏幕中上下左右的位置
            val top = l[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    open fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

}